var chargingStationData = [];
var parentNameData = [];
var lineKWHEntryData = [];
var flagDate = undefined;
var changeList = [];
var subBranchCompanyName = undefined;
var teamName = undefined;
var lineName = undefined;
var lineInfoData = [];
var lineNameData = [];
var reviewDateList = [];
var chargingKWHList = [];

$(document).ready(function() {
	showLoading();
	$('title', parent.document).html($('title').text());
	setBaseUrl();
	$ajaxList('searchBalanceInitSetting', getBalanceInitSetting);
	$ajaxList('branchCompany', getBranchCompany);
	createTableHead("lineKWHEntryThead", lineKWHEntryTable);
	setTimeout(hideLoading, 500);
});
function getBranchCompany(data) {
	var length = data.length;
	for (var i = 0;i < length; i++){
        $("#branchCompanyID").append("<option value='" + data[i].branchCompanyID + "'>" + data[i].branchCompanyName + "</option>");
    }
	$("#branchCompanyID").val("2");
	changeCompany();
}
function changeCompany() {
	parentNameData = [];
	lineNameData = [];
	var branchCompany = $("#branchCompanyID").val();
	if(branchCompany) {
		$ajaxList('lineName', getLineName, {branchCompanyID : $("#branchCompanyID").val()});
		$ajaxList('chargingStation', getChargingStation, {BulidStatus: '3', BranchCompanyID : $("#branchCompanyID").val()});
	} else {
		$("#branchCompanyID").tips({
			side : 2,
			msg : "请选择运营公司",
			bg : '#AE81FF',
			time : 2
		});
	}
}
function getBalanceInitSetting(data){
	var balanceInitSettingData = data.balanceInitSettingList[0]
	var balanceStartMonth = balanceInitSettingData && balanceInitSettingData.balanceStartMonth || new Date().getFullYear() + (new Date().getMonth() + 1 < 10 ? "0" + (new Date().getMonth() + 1) : new Date().getMonth() + 1);
	balanceDay = balanceInitSettingData.balanceDay;
	changeYear(0, balanceStartMonth);
	showMonth(getSystemTime().getMonth() + 1);
}
function showMonth(index){
	$('.activeMonthLi').removeClass("activeMonthLi");
	$("#li"+ index).addClass("activeMonthLi");
	index = index - 1;
	var year = $("#showYear").html().replace(/[^0-9]/ig,"");
	index = index >= 10 ? index : "0" + index;
	$("#reviewDate").val(date2String(stringToDate(year + "-" + index + "-" + balanceDay)));
}

function getChargingStation(data) {
	var length = data.length;
	chargingStationData = data;
	var item = undefined;
	for (var i = 0; i < length; i++) {
		$("#chargingStationID").append("<option value='" + data[i].chargingStationID + "'>" + data[i].chargingStationName + "</option>");
		item = {};
		item.ID = data[i].chargingStationID;
		item.label = data[i].chargingStationName;
		item.value = data[i].chargingStationName;
		parentNameData.push(item);
	}
	$(function(){
		autoComplete("name", parentNameData, '', "chargingStationID");
		bindInput("name", onInput);  
	});
}
function onInput(){
	$("#chargingStationID").val('');
}
function getChargingStationID(){
	var value = $("#name").val();
	if (!value) {
		$("#chargingStationID").val('');
	} else {
		if (!$("#chargingStationID").val() && parentNameData && parentNameData.length > 0) {
			var matcherData = filter(parentNameData, value);
			if (matcherData) {
				var length = matcherData.length;
				for (var i=0; i<length; i++) {
					if (matcherData[i] && matcherData[i].value == value) {
						$("#chargingStationID").val(matcherData[i].ID);
						break;
					}
				}
			}
		}
	}
}

function getLineName(data) {
	var length = data.length;
	lineInfoData = data;
	var item = undefined;
	for (var i = 0; i < length; i++) {
		$("#lineID").append("<option value='" + data[i].lineID + "'>" + data[i].lineName + "</option>");
		item = {};
		item.ID = data[i].lineID;
		item.label = data[i].lineName;
		item.value = data[i].lineName;
		lineNameData.push(item);
	}
	$(function(){
		autoComplete("line", lineNameData, '', "lineID");
		bindInput("line", onLineInput);  
	});
}
function onLineInput(){
	$("#lineID").val('');
}
function getLineID(){
	var value = $("#line").val();
	if (!value) {
		$("#lineID").val('');
	} else {
		if (!$("#lineID").val() && lineNameData && lineNameData.length > 0) {
			var matcherData = filter(lineNameData, value);
			if (matcherData) {
				var length = matcherData.length;
				for (var i=0; i<length; i++) {
					if (matcherData[i] && matcherData[i].value == value) {
						$("#lineID").val(matcherData[i].ID);
						break;
					}
				}
			}
		}
	}
}
function search(){
	if($("#name").val() == "") {
		$("#name").tips({
			side : 2,
			msg : "请选择充电站",
			bg : '#AE81FF',
			time : 2
		});
		$("#sureBtn").attr("hidden", true);
	} else if($("#line").val() == "") {
		$("#line").tips({
			side : 2,
			msg : "请选择线路",
			bg : '#AE81FF',
			time : 2
		});
		$("#sureBtn").attr("hidden", true);
	} else {
		$ajax('searchLineKWHEntry', 'lineKWHEntrySearch', searchLineKWHEntry);
	}
}

function searchLineKWHEntry(data){
	clearTable("lineKWHEntryTbody");
	lineKWHEntryData = data && data.lineKWHEntryList || [];
	for(var i = 0; i < lineInfoData.length; i++) {
		if($("#lineID").val() == lineInfoData[i].lineID) {
			lineName = lineInfoData[i].lineName;
			teamName = lineInfoData[i].teamName;
			subBranchCompanyName = lineInfoData[i].subBranchCompanyName;
			break;
		}
	}
	var nowDate = stringToDate($("#reviewDate").val());
	var maxDay = new Date(nowDate.getFullYear(), nowDate.getMonth()+1, 0).getDate();
	var tbody = $("#lineKWHEntryTbody");
	var array = $("#reviewDate").val().split("-");
	changeList = [];
	for(var i = 0; i < maxDay; i++){
		changeList.push(false);
		$tr = $('<tr>').appendTo(tbody);
		var hasFlag = true;
		var reviewDate = date2String(new Date(array[0], array[1] - 1, parseInt(array[2], 10) + i));
		$("<td>").html(reviewDate).appendTo($tr);
		$("<td>").html($("#name").val()).appendTo($tr);
		$("<td>").html(subBranchCompanyName).appendTo($tr);
		$("<td>").html(teamName).appendTo($tr);
		$("<td>").html(lineName).appendTo($tr);
		for(var j = 0; j < lineKWHEntryData.length; j++) {
			if(reviewDate == lineKWHEntryData[j].reviewDate) {
				$('<td id="lineKWH' + i + '">').html(lineKWHEntryData[j].sumChargingKWH + '<img src="static/images/detalisUpdate.png" onclick="changeLineKWH(' + i + ',' + j + ')">' + '<img src="static/images/detalisDelete.png" onclick="deleteLineKWH(' + j + ')">').appendTo($tr);
				hasFlag = false;
				break;
			}
		}
		if(hasFlag) {
			$("<td>").html('<input id="changeLineKWH' + i +'" style="text-align: center;" onchange="entryKWH(' + i + ')">').appendTo($tr);
		}
	}
	$("#sureBtn").attr("hidden", false);
}
function changeLineKWH(index, datai) {
	$("#lineKWH" + index).html('<input id="changeLineKWH' + index +'" value="' + lineKWHEntryData[datai].sumChargingKWH + '" style="text-align: center;" onblur="upperCase(' + index + ',' + datai + ')" onchange="entryKWH(' + index + ')">');
	$("#changeLineKWH" + index).focus();
}
function upperCase(index, datai) {
	lineKWHEntryData[datai].sumChargingKWH = $("#changeLineKWH" + index).val();
	$("#lineKWH" + index).html($("#changeLineKWH" + index).val() + '<img src="static/images/detalisUpdate.png" onclick="changeLineKWH(' + index + ',' + datai + ')">');
}
function entryKWH(index) {
	if(!$("#changeLineKWH" + index).val()) {
		changeList[index] = false;
	} else if(checkNum("changeLineKWH" + index)) {
		changeList[index] = true;
	}
}
function deleteLineKWH(index) {
	$ajax('deleteReviewRecord', {"ID": lineKWHEntryData[index].id}, deleteLineKWHResult);
}
function deleteLineKWHResult(data) {
	var result = data && data.result;
	if (result == "Success") {
		showMessge(messageContent["Delete.Success"]);
		search();
	} else if (result == "NotFound"){
		showMessge(messageContent["Delete.Failed"]);
	} else {
		showMessge(messageContent["Delete.Error"]);
	}
}
function confirm() {
	var totalChargingKWH = 0;
	for(var i = 0; i < changeList.length; i++) {
		if(changeList[i]) {
			if(/^[+-]?\d+(\.\d*)?$/.test($("#lineKWHEntryTbody tr").find('td:eq(5)')[i].outerText)) {
				totalChargingKWH = floatObj.add($("#lineKWHEntryTbody tr").find('td:eq(5)')[i].outerText, totalChargingKWH);
			} else {
				totalChargingKWH = floatObj.add($("#lineKWHEntryTbody tr").find('td:eq(5)')[i].children[0].value, totalChargingKWH);
			}
		} else {
			if(/^[+-]?\d+(\.\d*)?$/.test($("#lineKWHEntryTbody tr").find('td:eq(5)')[i].outerText)) {
				totalChargingKWH = floatObj.add($("#lineKWHEntryTbody tr").find('td:eq(5)')[i].outerText, totalChargingKWH);
			}
		}
	}
	showMessge("总电量为:" + totalChargingKWH, "model2");
}
function getUrl() {
	return 'saveLineKWHEntry';
}
function getData() {
	reviewDateList = [];
	chargingKWHList = [];
	for(var i = 0; i < changeList.length; i++) {
		if(changeList[i]) {
			reviewDateList.push($("#lineKWHEntryTbody tr").find('td:eq(0)')[i].innerHTML);
			if(/^[+-]?\d+(\.\d*)?$/.test($("#lineKWHEntryTbody tr").find('td:eq(5)')[i].outerText)) {
				chargingKWHList.push(parseFloat($("#lineKWHEntryTbody tr").find('td:eq(5)')[i].outerText, 10));
			} else {
				chargingKWHList.push(parseFloat($("#lineKWHEntryTbody tr").find('td:eq(5)')[i].children[0].value, 10));
			}
		}
	}
	return {reviewDateList: reviewDateList.toString(), chargingKWHList: chargingKWHList.toString(), ChargingStationName: $("#name").val(), SubBranchCompanyName: subBranchCompanyName, TeamName: teamName, LineName: lineName};
}
function sure(data){
	var result = data && data.result;
	if (result == "Success") {
		showMessge(messageContent["Insert.Success"]);
		search();
	} else if (result == "NotFound"){
		showMessge(messageContent["Insert.Failed"]);
	} else {
		showMessge(messageContent["Insert.Error"]);
	}
}